//
//  KLLocationHelper.m
//  KLCurrency
//
//  Created by Apple on 2019/6/21.
//  Copyright © 2019 bonc. All rights reserved.
//

#import "KLLocationHelper.h"
#import <UIKit/UIKit.h>

#define isIOS(version) ([[UIDevice currentDevice].systemVersion floatValue] >= version)

@interface KLLocationHelper()<CLLocationManagerDelegate>

@property(nonatomic,copy) LocationBlock block;
/** manager */
@property(nonatomic,strong) CLLocationManager *locationManager;

@end

@implementation KLLocationHelper

static KLLocationHelper *instance;

+ (instancetype)sharedInstance {
    //Singleton instance
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}

#pragma mark - lazy load
- (CLLocationManager *)locationManager
{
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
        
        //获取info.plist里的键值对
        NSDictionary *infoDict = [NSBundle mainBundle].infoDictionary;
        if (isIOS(8.0)) {
            //获取后台定位描述
            NSString *alwaysStr = infoDict[@"NSLocationAlwaysUsageDescription"];
            NSString *whenUserStr = infoDict[@"NSLocationWhenInUseUsageDescription"];
            // 根据开发者的设置 请求定位授权
            if ([alwaysStr length] > 0) {
                [_locationManager requestAlwaysAuthorization];
            }else if ([whenUserStr length] > 0){
                [_locationManager requestWhenInUseAuthorization];
                NSArray *backModels = infoDict[@"UIBackgroundModes"];
                if (![backModels containsObject:@"location"]) {
                    //前台定位授权，如果想在后台获取位置，需勾选后台模式location update
                }else{
                    if (isIOS(9.0)) {
                        _locationManager.allowsBackgroundLocationUpdates = YES;
                    }
                }
            }
        }else{
            // 如果请求的是前台定位授权, 如果想要在后台获取用户位置, 提醒其他开发者, 勾选后台模式location updates
            NSArray *backModes = infoDict[@"UIBackgroundModes"];
            if (![backModes containsObject:@"location"]) {
                KLLog(@"当前授权模式, 如果想要在后台获取位置, 需要勾选后台模式location updates");
            }
        }
    }
    
    return _locationManager;
}

#pragma mark - method
- (void)getCurrentLocation:(LocationBlock)block {
    self.block = block;
    //获取位置信息
    if ([CLLocationManager locationServicesEnabled]) {
        [self.locationManager startUpdatingLocation];
    }else{
        self.block(nil, nil, @"定位服务未开启");
    }
}

#pragma mark - <CLLocationManagerDelegate>
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //判断位置是否可用
    if (location.horizontalAccuracy >= 0) {
        [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (error == nil) {
                CLPlacemark *placemark = [placemarks firstObject];
                self.block(location, placemark, nil);
            }else{
                self.block(location, nil, @"反地理编码失败");
            }
        }];
    }
    [manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    self.block(nil, nil, @"获取定位失败");
    [manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            KLLog(@"用户还未决定");
            break;
        case kCLAuthorizationStatusRestricted:{
            KLLog(@"访问受限");
            //定位关闭 或 对此APP授权未never时调用
            self.block(nil, nil, @"暂无定位权限");
        }
            break;
        case kCLAuthorizationStatusDenied:{
            if ([CLLocationManager locationServicesEnabled]) {
                KLLog(@"定位开启，但被拒");
                self.block(nil, nil, @"定位请求被拒绝");
            }else{
                KLLog(@"定位关闭，不可用");
                self.block(nil, nil, @"定位被关闭不可用");
            }
        }
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            KLLog(@"获取前后台定位授权");
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            KLLog(@"获取前台定位授权");
            break;
        default:
            break;
    }
}

@end
